//
//  AppDelegate.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-6-13.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "AppDelegate.h"
#import "UncaughtExceptionHandler.h"
#import "MMDrawerController.h"
#import "MMDrawerVisualState.h"
#import "DBUtil.h"
#import "MessageService.h"
#import "Message.h"
#import "AlertService.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "HCMacroDefinition.h"
#import "HelpViewController.h"
#import "HCSendHttpOperation.h"

BMKMapManager* _mapManager;

@interface AppDelegate()
@property (nonatomic,strong) MBProgressHUD*HUD;
@property (nonatomic) BOOL appReachable;

@end

@implementation AppDelegate
@synthesize flag;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    InstallUncaughtExceptionHandler();

    //检测网络
    
    [self useReachability];
    
    //HC
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(loadWaitView) name:@"HCLOAD" object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(removeLoad) name:@"HCREMOVE" object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(tip:) name:@"HCTIP" object:nil];
    locationManager = [[CLLocationManager alloc]init];
    locationManager.delegate = self;
    //app=[[UIApplication sharedApplication] delegate];

    
    //消息推送支持的类型
    UIRemoteNotificationType types =
    (UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert);
    //注册消息推送
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    
    //
    MMDrawerController * drawerController = (MMDrawerController *)self.window.rootViewController;
    [drawerController setMaximumLeftDrawerWidth:210.0];
    [drawerController setMaximumRightDrawerWidth:200.0];
    [drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    
    drawerController.shouldStretchDrawer = NO;

    
    //旅游
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"IKy8EtkKcYFygR4g1o5eSIs8" generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }

    //本地提醒
    [[AlertService sharedCenter] clearNotifications];
    [[AlertService sharedCenter] reloadData];
    [[AlertService sharedCenter] scheduleEventLocalNotification];
    [[AlertService sharedCenter] scheduleDailyLocalNotification];
    
    //蓝牙
    [self detectBluetooth];
    
    [self.window makeKeyAndVisible];
    
    
    //第一次打开
    NSNumber* isFirst = [[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstLaunch"];
    if (nil == isFirst) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"HCSHOW1"];
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"HCSHOW2"];
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"HCSHOW3"];
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"HCSHOW4"];
        
        isFirst = [NSNumber numberWithBool:NO];
        [[NSUserDefaults standardUserDefaults] setObject:isFirst forKey:@"isFirstLaunch"];
        
        UIStoryboard *mainstoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        HelpViewController *helpVC = [mainstoryboard instantiateViewControllerWithIdentifier:@"helpVC"];
        [self.window.rootViewController presentViewController:helpVC animated:NO completion:NULL];
    }
    
    
    return YES;
}

#pragma HC
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
    CLBeaconRegion *beaconRegion = (CLBeaconRegion *)region;
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/HCibeacon.plist"];
    
    NSMutableDictionary *compareTime = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
    if (![[compareTime objectForKey:beaconRegion.proximityUUID.UUIDString] isKindOfClass:[NSDate class]]) {
        //第一次进入应用
        [compareTime setObject:[NSDate date] forKey:beaconRegion.proximityUUID.UUIDString];
        [compareTime writeToFile:path atomically:YES];
        [self sendLocalNotification:beaconRegion.proximityUUID.UUIDString];
        NSLog(@"beacon.proximityUUID.UUIDString--->%@",beaconRegion.proximityUUID.UUIDString);
    }else{
        NSDate *backup = [compareTime objectForKey:beaconRegion.proximityUUID.UUIDString];
        NSDate *now = [NSDate date];
        NSTimeInterval cha = [now timeIntervalSinceDate:backup];
        NSLog(@"cha--->%f",cha);
        if (cha > TIME_DEAL) {
            [self sendLocalNotification:beaconRegion.proximityUUID.UUIDString];
            [compareTime setObject:[NSDate date] forKey:beaconRegion.proximityUUID.UUIDString];
            [compareTime writeToFile:path atomically:YES];
        }
    }
}


- (void)sendLocalNotification:(NSString *)uuid
{
    UILocalNotification *notice = [[UILocalNotification alloc] init];
    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"HCResource" withExtension:@"bundle"]];
    NSDictionary *infoList = [[NSDictionary alloc]initWithContentsOfFile:[bundle pathForResource:@"HCUUIDNameList" ofType:@"plist"]];
    NSString *param = [NSString stringWithFormat:@"%@",[infoList objectForKey:uuid]];
    notice.alertBody = param;
    notice.userInfo = @{@"uuid":uuid};
    notice.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:notice];
    
    HCSendHttpOperation *sendHttpOperation = [HCSendHttpOperation shareSendHttpRequest];
    [sendHttpOperation getDataWithUUID:uuid];
    NSLog(@"http请求了");
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSInteger flag2 = UIInterfaceOrientationMaskAll;
    NSLog(@"flag-->%d",app.flag);
    if(app.flag != 1)
        return UIInterfaceOrientationMaskPortrait;
    return flag2;
}

//加载界面
- (void)loadWaitView
{
    if(loadView)
        loadView = nil;
    
    loadView = [[HCCustomLoad alloc] initWithFrame:[[UIScreen mainScreen] bounds]
                                          loadType:0
                                               msg:@""];
    [self.window addSubview:loadView];
}

//移除加载界面
- (void)removeLoad
{
    if(loadView)
        [loadView removeFromSuperview];
}

- (void)tip:(NSNotification *)noti
{
    id a = [noti object];
    NSString *msg = [a objectForKey:@"HCmsg"];
    
    if(loadView)
    {
        [loadView removeFromSuperview];
        loadView = nil;
    }
    loadView = [[HCCustomLoad alloc] initWithFrame:CGRectMake(30, [[UIScreen mainScreen] bounds].size.height - 100, 260, 30+26*(2-1))
                                          loadType:1
                                               msg:msg];
    [self.window addSubview:loadView];
}


#pragma useReachability
-(void)useReachability
{
    self.appReachable = YES;
    
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(reachabilityChanged:)
                                                name: kReachabilityChangedNotification
                                              object: nil];
    
    [reach startNotifier];
}


-(void)reachabilityChanged:(NSNotification *)note {
    
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status == NotReachable) {
        self.appReachable = NO;
        [self showUnReachable];
        NSLog(@"网络异常");
    }else{
        self.appReachable = YES;
        NSLog(@"网络恢复正常");
    }
}


-(void)showUnReachable
{
    if (self.HUD==nil) {
        self.HUD = [[MBProgressHUD alloc] initWithWindow:self.window];
        [self.window addSubview:self.HUD];
        self.HUD.mode = MBProgressHUDModeText;
        self.HUD.labelText = NSLocalizedString(@"网络状况不佳", nil);
    }

    [self.HUD show:YES];
    [self.HUD hide:YES afterDelay:1.3];
}

-(BOOL)isAppReachable{
    if (!self.appReachable) {
        [self showUnReachable];
    }
    return self.appReachable;
}

#pragma Push
- (void)applicationDidBecomeActive:(UIApplication *)application{
    NSLog(@"applicationDidBecomeActive");
    //
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"deviceToken: %@", deviceToken);
    
    if ([self isAppReachable]) {
        [[[MessageService alloc] init] pushDeviceToken:deviceToken completion:^(id result, NSError *error) {
            if (error == nil) {
                NSLog(@"发送Token成功");
            }
        }];
    }
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    
    NSLog(@"%@", str);
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    Message *msg = [[Message alloc] instance:[userInfo objectForKey:@"content"]];
    [[[MessageService alloc] init] addMessage:msg];
    
    NSLog(@"收到推送");
}

//蓝牙
- (void)detectBluetooth
{
    if(!self.bluetoothManager)
    {
        // Put on main queue so we can call UIAlertView from delegate callbacks.
        self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()] ;
    }
    [self centralManagerDidUpdateState:self.bluetoothManager]; // Show initial state
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(self.bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
}

@end
